package br.com.busgps.crawler;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.busgps.util.Constants;

import com.google.gson.JsonSyntaxException;

/**
*
* <b>Descricao da Classe:</b><br>
* 
* Job responsavel por obter todas as linhas de onibus.
*
* @author rodrigo.bacellar
* @since 10/09/2014
*
*/
public class CrawlerBusLines implements Job
{
    private static Logger logger = LoggerFactory.getLogger(CrawlerBusLines.class);

    public void execute(JobExecutionContext arg0) throws JobExecutionException
    {
        logger.info("Job Started - " + getClass().getSimpleName() + "");

        List<String> buses = new ArrayList<String>();

        try
        {
            /** CRIA UMA CONEXAO E RECUPERA O HTML */
            Document doc = Jsoup.connect(Constants.REQUEST_LINES_URL).get();

            /** VARRE O CODIGO FONTE E FAZ MATCH PELA TAG */
            Elements lines = doc.select(Constants.HTML_TAG_PATTERN);

            /** REMOVE O ULTIMO ITEM POIS EH APENAS UMA DESCRICAO */
            lines.last().remove();

            for (Element el : lines)
            {
                buses.add(el.text());
            }
        }
        catch (MalformedURLException e)
        {
            logger.error("Erro no formato da URL. " + e);
        }
        catch (IOException e)
        {
            logger.error("Erro de I/O na conexao. " + e);
        }
        catch (JsonSyntaxException e)
        {
            logger.error("Erro de formatacao no json. " + e);
        }
        System.out.println(buses);

        logger.info("Job Finished - " + getClass().getSimpleName() + "");
    }
}